<template>
  <el-menu ref="menu" style="height: 100%;" @open="open" @close="close" :collapse="collapse" :collapse-transition="false"
           background-color="#334054" text-color="#c1cbd8" active-text-color="#5a9cf8" :default-active="currentRouteName"
          :style="{minWidth: menuMinWidth}">
    <template v-for="item of menu">
      <el-menu-item v-if="!item.children" :key="item.routeName" :index="item.routeName"
                    @click="toRoute(item.routeName)"
                    :class="[subMenuAction(item) ? 'action' : undefined]">
        <i :class="[item.icon]"></i>
        <span slot="title">{{ item.name }}</span>
      </el-menu-item>
      <el-submenu v-else :key="item.name" :index="item.name" :popper-append-to-body="true">
        <template slot="title">
          <i :class="[item.icon]"></i>
          <span slot="title">{{ item.name }}</span>
        </template>
        <el-menu-item v-for="subItem of item.children" :key="subItem.routeName" :index="subItem.routeName"
                      @click="toRoute(subItem.routeName)"
                      :class="[subMenuAction(subItem) ? 'action' : undefined]">
          <i :class="[subItem.icon]"></i>
          <span slot="title">{{ subItem.name }}</span>
        </el-menu-item>
      </el-submenu>
    </template>
  </el-menu>
</template>

<script>
import {menu} from "@/init/menu.js";

export default {
  name: 'xt-sidebar',
  data() {
    return {
      menu,
      menuMinWidth: '64px'
    }
  },
  computed: {
    currentRouteName() {
      return this.xtGetter('menu', 'getCurrentRouteName')
    },
    openedSubMenuIndexs() {
      return this.xtGetter('menu', 'getOpenedSubMenuIndexs')
    },
    collapse() {
      return this.xtGetter('top', 'getMenuClose')
    }
  },
  mounted() {
    this.openMenu()
  },
  watch: {
    collapse(newValue) {
      if (!newValue) {
        this.menuMinWidth = '200px'
        this.openMenu()
      } else {
        this.menuMinWidth = '64px'
      }
    }
  },
  methods: {
    subMenuAction(item) {
      return item.routeName === this.currentRouteName
    },
    toRoute(routeName) {
      this.xtPush(routeName)
    },
    open(index) {
      let openedSubMenuIndexs = this.openedSubMenuIndexs
      let has = openedSubMenuIndexs.some(item => item === index)
      if (has) {
        return
      }
      openedSubMenuIndexs.push(index)
      this.xtMutation('menu', 'setOpenedSubMenuIndexs', openedSubMenuIndexs)
    },
    close(index) {
      let openedSubMenuIndexs = this.openedSubMenuIndexs
      openedSubMenuIndexs = openedSubMenuIndexs.filter(item => item !== index)
      this.xtMutation('menu', 'setOpenedSubMenuIndexs', openedSubMenuIndexs)
    },
    openMenu() {
      if (this.collapse) {
        this.menuMinWidth = '64px'
        return
      }
      this.menuMinWidth = '200px'
      let menu = this.$refs.menu
      for (let index of this.openedSubMenuIndexs) {
        menu.open(index)
      }
    }
  }
}
</script>